package com.medical.utils;



import com.medical.constants.APIConstant;
import com.medical.model.param.ModelsMessage;
import com.medical.model.param.OllamaModels;
import com.medical.model.ro.OllamaListModelResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2025/6/13 22:49
 * @desc
 */
@Component
public class ModelsUtils {
    private static final Logger log = LoggerFactory.getLogger(ModelsUtils.class);
    private final WebClient webClient;

    public ModelsUtils() {
        this.webClient = WebClient.builder()
                .baseUrl(APIConstant.OLLAMA_MODEL_LIST_URL)
                .build();
    }

    public List<OllamaModels> getModelsList() {
        log.info("开始获取 Ollama 模型列表...");

        try {
            Mono<OllamaListModelResponse> responseMono = webClient.get()
                    .uri("/api/tags")
                    .retrieve()
                    .bodyToMono(OllamaListModelResponse.class);

            OllamaListModelResponse response = responseMono.block();

            if (response == null) {
                log.warn("Ollama 返回响应为空");
                return List.of();
            }

            if (response.getModels() == null) {
                log.warn("Ollama 返回模型列表字段为 null");
                return List.of();
            }
            log.info("模型列表- {}", response.getModels());
            List<OllamaModels> models = response.getModels().stream()
                    .map(m -> {
                        OllamaModels model = new OllamaModels();
                        model.setName(m.getName());
                        model.setModel(m.getModel());
                        model.setModifiedAt(m.getModifiedAt());
                        model.setSize(m.getSize());
                        model.setDigest(m.getDigest());
                        model.setDetails(m.getDetails());
                        return model;
                    })
                    .collect(Collectors.toList());

            log.info("成功获取到 {} 个模型", models.size());
            for (OllamaModels m : models) {
                log.debug("模型名称：{}", m.getName());
            }

            return models;

        } catch (Exception e) {
            log.error("获取 Ollama 模型列表时发生异常", e);
            return List.of();
        }
    }
    public ModelsMessage getModelsMessage(String name){
        log.info("开始获取{}模型信息...",  name);
        try {
            String requestBody = String.format("{\"model\":\"%s\"}", name);

            Mono<ModelsMessage> responseMono = webClient.post()
                    .uri("/api/show")
                    .body(BodyInserters.fromValue(requestBody))
                    .retrieve()
                    .bodyToMono(ModelsMessage.class);

            ModelsMessage response = responseMono.block();

            if (response == null) {
                log.warn("Ollama 返回响应为空");
                return null;
            }
            if (response.getModelfile() == null) {
                log.warn("Ollama 模型信息字段为 null");
                return null;
            }
            log.info("模型信息- {}", response.toString());
            return  response;
        }catch (Exception e) {
            log.error("获取 Ollama 模型信息时发生异常", e);
            return null;
        }
    }
}